<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use think\response\Json;
use app\api\model\User as UserModel;
use app\api\model\dealer\User as DealerUserModel;
use app\api\model\dealer\Setting as SettingModel;
use app\api\service\User as UserService;
use cores\exception\BaseException;

/**
 * 分销中心
 * Class Dealer
 * @package app\api\controller\user
 */
class Dealer extends Controller
{
    // 当前用户信息
    /* @var UserModel $user */
    private UserModel $user;

    // 当前分销商信息
    private ?DealerUserModel $dealer;

    // 分销商设置
    private array $setting;

    /**
     * 构造方法
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function initialize()
    {
        parent::initialize();
        // 用户信息
        $this->user = UserService::getCurrentLoginUser(true);
        // 分销商用户信息
        $this->dealer = DealerUserModel::detail(UserService::getCurrentLoginUserId());
        // 分销商设置
        $this->setting = SettingModel::getAll();
    }

    /**
     * 分销商中心
     * @return Json
     * @throws BaseException
     */
    public function center(): Json
    {
        // 获取用户头像
        $this->user = UserModel::related($this->user, ['avatar']);
        return $this->renderSuccess([
            // 当前是否为分销商
            'isDealer' => $this->isDealerUser(),
            // 当前用户信息
            'user' => $this->user,
            // 分销商用户信息
            'dealer' => $this->dealer,
            // 推荐人昵称
            'refereeName' => DealerUserModel::getRefereeName(),
            // 分销设置
            'setting' => [
                // 背景图
                'background' => $this->setting['background']['index'],
                // 页面文字
                'words' => $this->setting['words']
            ]
        ]);
    }

    /**
     * 分销商用户详情
     * @return Json
     * @throws BaseException
     */
    public function user(): Json
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 分销商用户详情
        $dealer = DealerUserModel::detail($userId);
        return $this->renderSuccess(compact('dealer'));
    }

    /**
     * 当前用户是否为分销商
     * @return bool
     */
    private function isDealerUser(): bool
    {
        return !empty($this->dealer) && !$this->dealer['is_delete'];
    }
}